//
//  SessionMessageViewController.m
//  AirMessage
//
//  Created by 陈区 on 13-1-29.
//  Copyright (c) 2013年 陈区. All rights reserved.
//

#import "SEGOrderMessageViewController.h"
#import "SEGSessionMessageViewController.h"

#import "SessionMessageCell.h"

#import "SEGSessionMessageViewModel.h"

//两条消息的时间间隔
#define kMessageTimeInterval 600 //600秒

@interface SEGSessionMessageViewController ()
<UITableViewDelegate,
UITableViewDataSource,
SessionMessageCellDelegete,
UITextViewDelegate>

/// 表格
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *footerView;
@property (nonatomic, strong) UITextView *inputTextView;
/// 发送按钮
@property (nonatomic, strong) UIButton *btnSendMsg;
@property (nonatomic, assign) CGRect footerViewFrame;
@property (nonatomic, assign) CGSize kbSize;

/// viewModel
@property (nonatomic, strong) SEGSessionMessageViewModel *viewModel;

@end

@implementation SEGSessionMessageViewController
@synthesize messageModel;

CGFloat firstHeaderHeight = 40;
CGFloat otherHeaderHeight = 27;
CGFloat footerViewHeight = 49;

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
    [self scrollTableToFoot];
    
    //当界面显示时，重新判断
    self.btnSendMsg.enabled = YES;
    self.inputTextView.editable = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self showCustomNavigationBackButton];
    if (self.messageModel.sender && self.messageModel.sender.length > 0) {
        self.title = self.messageModel.sender;
    }
    
    // UI
    [self.view addSubview:self.tableView];
    self.footerViewFrame = CGRectMake(0, CGRectGetHeight(self.view.bounds) - kNavigationBarAndStatusBarHeight -  footerViewHeight - LYSafeAreaBottom(), CGRectGetWidth(self.view.bounds), footerViewHeight + LYSafeAreaBottom());
    [self.view addSubview:self.footerView];
    [self.footerView addSubview:self.inputTextView];
    [self.footerView addSubview:self.btnSendMsg];
    
    // 通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillHideNotification:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillShowNotification:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onReceiveMessageNotification:)
                                                 name:RECEIVE_MESSAGE_UI
                                               object:nil];
}

#pragma mark - UI
//滚动表格到最后一行
- (void)scrollTableToFoot {
    NSInteger s = [self.tableView numberOfSections];
    if (s < 1) return;
    NSInteger r = [self.tableView numberOfRowsInSection:s - 1];
    if (r < 1) return;
    
    NSIndexPath* ip = [NSIndexPath indexPathForRow:r - 1 inSection:s - 1];
    [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}
//滚动表格到第一行
- (void)scrollTableToTop {
    NSInteger s = [self.tableView numberOfSections];
    if (s < 1) return;
    NSInteger r = [self.tableView numberOfRowsInSection:0];
    if (r < 1) return;
    
    NSIndexPath* ip = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
//滚动到指定行
- (void)scrollTableToIndexPath:(NSIndexPath*)indexPath {
    NSInteger s = [self.tableView numberOfSections];
    if (s < indexPath.section) return;
    NSInteger r = [self.tableView numberOfRowsInSection:s];
    if (r < indexPath.row) return;
    
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}
 
#pragma mark <UITableViewDelegate, UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.viewModel.messageArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* cellIdStr = @"CellReuse";
    SessionMessageCell* cell = (SessionMessageCell*)[tableView dequeueReusableCellWithIdentifier:cellIdStr];
    if (!cell) {
        cell = [[SessionMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdStr];
        cell.cellDelegate = self;
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    cell.index = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
    //把显示表格值放到这，避免多次调用[cell reloadMessage:sessionMsg];方法
    MessageModel* model = [self.viewModel.messageArray objectAtIndex:indexPath.section];
    [cell reloadMessage:model];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    //单元格头的高度
    CGFloat headerHeight = 0.0;
    long section = indexPath.section;
    if (section == 0) {
        headerHeight = firstHeaderHeight;
    } else {
        long forwardIndex = section - 1;
        if (forwardIndex >= 0 && [self.viewModel.messageArray count] > forwardIndex) {
            MessageModel* forwardMsg = [self.viewModel.messageArray objectAtIndex:forwardIndex];
            MessageModel* curMsg = [self.viewModel.messageArray objectAtIndex:section];
            NSDate* forwardDate = [SEGUtils dateFromString:forwardMsg.createTime withFormatString:@"yyyy-MM-dd HH:mm"];
            NSDate* currentDate = [SEGUtils dateFromString:curMsg.createTime withFormatString:@"yyyy-MM-dd HH:mm"];
            if (forwardDate && currentDate) {
                NSTimeInterval interval = [currentDate timeIntervalSinceDate:forwardDate];
                if (interval >= kMessageTimeInterval) {
                    headerHeight = otherHeaderHeight;
                }
            }
        }
    }
    
    //内容的高度
    MessageModel* sessionMsg = [self.viewModel.messageArray objectAtIndex:indexPath.section];
    CGFloat contentHeight = [self heightForCellWithMessage:sessionMsg];
    
    //整个单元格的高度
    CGFloat cellHeight = contentHeight + headerHeight;
    return cellHeight;
}
#pragma mark - UIScrollDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView {
    [self.inputTextView resignFirstResponder];
}

- (CGFloat)heightForCellWithMessage:(MessageModel*)aMessage {
    float cellHeight = 0.0f;
    float bubbleHeight = 0;
    //contenttype 1：文本   2图片 5：借条    else：默认文本
    if ([aMessage.contenttype isEqualToString:@"1"]) { // 文本
        CGSize size = [aMessage.message boundingRectWithSize:CGSizeMake(IM_CELL_MAX_WIDTH - 24, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:15] } context:nil].size;
        size.height += 20;
        
        //判断气泡的最小高度，不能小于规定的最小值
        bubbleHeight = size.height < IM_CELL_MIN_HEIGHT ? IM_CELL_MIN_HEIGHT : size.height;
    }

    cellHeight = bubbleHeight + 17;
    return cellHeight;
}

#pragma mark - Event
- (void)handleTapGesture:(UITapGestureRecognizer *)gestureRecognizer {
    [self.inputTextView resignFirstResponder];
}
//返回
- (void)onNavigationLeftButtonClicked:(UIButton *)sender {
    self.tableView = nil;
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}
// 发送按钮点击
- (void)btnSendMsgClicked:(UIButton *)sender {
    NSString *message = [self.inputTextView.text copy];
    if (![message isEqualToString:@""]) {
        NSString* temp = [message stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (temp.length == 0) return;
        
        [self sendMessageForString:message];
        self.inputTextView.text = @"";
    }
    [self performSelector:@selector(scrollTableToFoot) withObject:nil afterDelay:0.1];
}
#pragma mark - 发送消息
//发送消息
- (void)sendMessageForString:(NSString *)message {
    [SVProgressHUD show];
    @weakify(self);
    [[self.viewModel.sendMsgCommand execute:message] subscribeNext:^(id  _Nullable x) {
        [SVProgressHUD dismiss];
        @strongify(self);
        //回到主线程 刷新界面
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}

#pragma mark - TextViewDelegate
- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text; {
    if ([text isEqualToString:@"\n"]) { //点击发送按钮
        [self btnSendMsgClicked:nil];
        return NO;
    }
    return YES;
}
- (void)textViewDidChange:(UITextView*)textView; {
    CGSize size = STRING_SIZE_FONT(self.view.frame.size.width - 83, textView.text, 14);
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    if (size.height < 33) {
        self.footerView.frame = CGRectMake(0, self.view.frame.size.height - self.kbSize.height - footerViewHeight, self.footerView.frame.size.width, footerViewHeight);
        self.footerViewFrame = CGRectMake(0, self.view.frame.size.height - footerViewHeight - LYSafeAreaBottom(), self.footerView.frame.size.width, footerViewHeight + LYSafeAreaBottom());
        self.inputTextView.frame = CGRectMake(15, 7, self.view.frame.size.width - 85, 35);
    }
    else {
        self.footerView.frame = CGRectMake(0, self.view.frame.size.height - self.kbSize.height - 32 - size.height, self.footerView.frame.size.width, size.height + 32);
        self.footerViewFrame = CGRectMake(0, self.view.frame.size.height - 32 - size.height, self.footerView.frame.size.width, size.height + 32);
        self.inputTextView.frame = CGRectMake(15, 7, self.view.frame.size.width - 85, size.height + 16);
    }
    [UIView commitAnimations];
}

#pragma mark - SessionMessageCellDelegete
//cell的头部视图 时间
- (UIView *)sessionMessageCell:(SessionMessageCell *)aMsgCell viewForHeaderInCell:(NSIndexPath *)index {
    UIView *headerView = nil;
    if (index.section >= [self.viewModel.messageArray count]) return nil;
        
    BOOL isShowTime = false;
    long section = index.section;
    MessageModel *curMsg = [self.viewModel.messageArray objectAtIndex:section];
    if (!curMsg.createTime) return headerView;
    
    if (section == 0) {
        isShowTime = YES;
    } else {
        long forwardIndex = section - 1;
        if (forwardIndex >= 0 && [self.viewModel.messageArray count] > forwardIndex) {
            MessageModel* forwardMsg = [self.viewModel.messageArray objectAtIndex:forwardIndex];
            NSDate* forwardDate = [SEGUtils dateFromString:forwardMsg.createTime withFormatString:@"yyyy-MM-dd HH:mm"];
            NSDate* currentDate = [SEGUtils dateFromString:curMsg.createTime withFormatString:@"yyyy-MM-dd HH:mm"];
            if (forwardDate && currentDate) {
                NSTimeInterval interval = [currentDate timeIntervalSinceDate:forwardDate];
                if (interval >= kMessageTimeInterval) {
                    isShowTime = YES;
                }
            }
        }
    }
    
    if (isShowTime) {
        CGFloat headerHeight;
        if (section == 0) {
            headerHeight = firstHeaderHeight;
        }
        else {
            headerHeight = otherHeaderHeight;
        }
        headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), headerHeight)];
        headerView.backgroundColor = [UIColor clearColor];
        
        NSString *timeStr = [SEGUtils getTimeStringInMessageDetailVCWithString:curMsg.createTime];
        UILabel* timeLbl = [[UILabel alloc] init];
        timeLbl.textColor = kColor_3;
        timeLbl.backgroundColor = [UIColor clearColor];
        timeLbl.font = kFont_13;
        timeLbl.text = timeStr;
        [headerView addSubview:timeLbl];
        [timeLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(headerView);
            make.bottom.equalTo(headerView).offset(-13);
        }];
    }
    return headerView;
}

#pragma mark - NSNotification
- (void)onKeyboardWillHideNotification:(NSNotification*)aNotification {
    double timer = [aNotification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:timer animations:^{
        self.footerView.frame = self.footerViewFrame;
        CGRect newFrame = self.tableView.frame;
        newFrame.size.height = self.footerViewFrame.origin.y;
        self.tableView.frame = newFrame;
    }];
}
- (void)onKeyboardWillShowNotification:(NSNotification*)aNotification {
    self.kbSize = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    double timer = [aNotification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:timer animations:^{
        CGRect newFrame = self.footerViewFrame;
        newFrame.origin.y -= (self.kbSize.height - LYSafeAreaBottom());
        self.footerView.frame = newFrame;
        CGRect newTableViewFrame = self.tableView.frame;
        newTableViewFrame.size.height = newFrame.origin.y;
        self.tableView.frame = newTableViewFrame;
    }];

    [self scrollTableToFoot];
}
- (void)onReceiveMessageNotification:(NSNotification *)aNotification {
    @weakify(self);
    [self.viewModel.receiveSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self.tableView reloadData];
        [self performSelector:@selector(scrollTableToFoot) withObject:nil afterDelay:0.1];
    }];
}

#pragma mark - traitCollectionDidChange
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [self.tableView reloadData];
    [super traitCollectionDidChange:previousTraitCollection];
}

#pragma mark - Getter
- (SEGSessionMessageViewModel *)viewModel {
    if (!_viewModel) _viewModel = [[SEGSessionMessageViewModel alloc] initWithMessageModel:messageModel];
    return _viewModel;
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - kNavigationBarAndStatusBarHeight - footerViewHeight - LYSafeAreaBottom()) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = kColor_bg;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        //点击手势
        UITapGestureRecognizer* tapGestureRecognize = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                              action:@selector(handleTapGesture:)];
        [_tableView addGestureRecognizer:tapGestureRecognize];
    }
    return _tableView;
}
- (UIImageView *)footerView {
    if (!_footerView) {
        _footerView = [[UIImageView alloc] initWithFrame:self.footerViewFrame];
        _footerView.backgroundColor = kColor_TABLE;
        _footerView.userInteractionEnabled = YES;
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 0.5)];
        line.backgroundColor = kColor_L2;
        [_footerView addSubview:line];
    }
    return _footerView;
}
- (UITextView *)inputTextView {
    if (!_inputTextView) {
        _inputTextView = [[UITextView alloc] initWithFrame:CGRectMake(15, 8, CGRectGetWidth(self.view.bounds) - 85, 35)];
        _inputTextView.delegate = self;
        [_inputTextView setUserInteractionEnabled:YES];
        _inputTextView.font = [UIFont systemFontOfSize:14];
        _inputTextView.textColor = kColor_1;
        _inputTextView.scrollEnabled = NO;
        _inputTextView.layer.masksToBounds = YES;
        _inputTextView.layer.cornerRadius = 17.5;
        _inputTextView.returnKeyType = UIReturnKeySend;
        _inputTextView.backgroundColor = kColor_bg;
    }
    return _inputTextView;
}
- (UIButton *)btnSendMsg {
    if (!_btnSendMsg) {
        _btnSendMsg = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnSendMsg.frame = CGRectMake(CGRectGetWidth(self.view.bounds) - 54, 0, 40, footerViewHeight);
        [_btnSendMsg setTitle:@"发送" forState:UIControlStateNormal];
        [_btnSendMsg.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [_btnSendMsg setTitleColor:kColor_T forState:UIControlStateNormal];
        [_btnSendMsg addTarget:self
                        action:@selector(btnSendMsgClicked:)
              forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnSendMsg;
}

@end
